package alogrithm;

/**
 * @author lbw
 * @version 1.0
 * @date 2021/10/16 15:41
 */


public class AddInList {

    public ListNode addInList(ListNode head1, ListNode head2) {
        double d1 = 0.1239d;
        ListNode l1 = reverseList(head1);
        ListNode l2 = reverseList(head2);
        ListNode res = null;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int n1 = l1 == null ? 0 : l1.val;
            int n2 = l2 == null ? 0 : l2.val;
            int sum = n1 + n2;
            ListNode tmp = new ListNode(sum % 10);
            carry = sum / 10;
            tmp.next = res;
            res = tmp;
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }
        if (carry > 0) {
            ListNode tmp = new ListNode(carry);
            tmp.next = res;
            res = tmp;
        }
        return res;
    }

    private ListNode reverseList(ListNode head) {
        ListNode curr = head;
        ListNode prev = null;
        while (curr != null) {
            ListNode tmp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = tmp;
        }
        return prev;
    }

    static class ListNode {
        int val;
        ListNode next = null;

        public ListNode(int val) {
            this.val = val;
        }
    }
}
